package cn.szsys.integration.config.filter.wrapper;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import lombok.Getter;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Ryan
 * @since 2025-05-08
 **/
@Getter
public class HeaderBase6DecodeRequestWrapper extends HttpServletRequestWrapper {

    private final Map<String, String> customHeaders = new HashMap<>();

    public HeaderBase6DecodeRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    /**
     * 添加header
     *
     * @param name  name
     * @param value value
     * @author Ryan
     */
    public void addHeader(String name, String value) {
        customHeaders.put(name, value);
    }

    /**
     * 添加headerMap
     *
     * @param map map
     * @author Ryan
     */
    public void addHeaders(Map<String, String> map) {
        customHeaders.putAll(map);
    }

    /**
     * 获取全部header
     *
     * @return {@link Map< String, String>}
     * @author Ryan
     */
    public Map<String, String> getHeaders() {
        Map<String, String> headerMap = new HashMap<>();
        // 获取原始请求的 Header 名称
        java.util.List<String> headerNames = java.util.Collections.list(super.getHeaderNames());
        for (String headerName : headerNames) {
            headerMap.put(headerName, this.getHeader(headerName));
        }
        return headerMap;
    }

    @Override
    public String getHeader(String name) {
        // 优先返回自定义的 Header
        if (customHeaders.containsKey(name)) {
            return customHeaders.get(name);
        }
        // 否则返回原始请求的 Header
        return super.getHeader(name);
    }

    @Override
    public java.util.Enumeration<String> getHeaderNames() {
        // 获取原始请求的 Header 名称
        java.util.List<String> headerNames = java.util.Collections.list(super.getHeaderNames());
        // 添加自定义的 Header
        headerNames.addAll(customHeaders.keySet());
        return java.util.Collections.enumeration(headerNames);
    }

    @Override
    public java.util.Enumeration<String> getHeaders(String name) {
        if (customHeaders.containsKey(name)) {
            return java.util.Collections.enumeration(java.util.List.of(customHeaders.get(name)));
        }
        return super.getHeaders(name);
    }
}
